package 回溯;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class q90子集2 {

    public static void main(String[] args) {

        int[] nums = {1, 2, 2};
        Solution solution = new q90子集2().new Solution();
        solution.subsetsWithDup(nums);
    }
    class Solution {
        List<List<Integer>> res = new ArrayList<>();
        LinkedList<Integer> path = new LinkedList<>();

        boolean[] used;
        public List<List<Integer>> subsetsWithDup(int[] nums) {
            // 此时集合中可以有重复元素，需要另外注意树层去重
            Arrays.sort(nums);
            res.add(new ArrayList<>(path)); // 先放入一个空集合

            used = new boolean[nums.length];
            backtracking(nums, 0);
            return res;
        }

        public void backtracking(int[] nums, int startIndex) {

            if (startIndex == nums.length) {

                return;
            }


            for (int i = startIndex; i < nums.length; i++) {
                if(i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) continue;  // 同树层 不可选相同元素
                path.push(nums[i]);
                used[i] = true;
                res.add(new ArrayList<>(path));
                backtracking(nums, i + 1);
                used[i] = false;
                path.pop();
            }
        }
    }
}
